package com.coos.util;
import java.io.UnsupportedEncodingException;

public class SubStringTest {

	public static void main(String[] args) {
		String inStr = "我ABC";
		String str = subString(inStr, 4);
		System.out.println(str);

		inStr = "我ABC汉DEF";
		str = subString(inStr, 6);
		System.out.println(str);

	}

	/**
	 * 字符串按字节截取
	 * @param str 原字符
	 * @param len 截取长度
	 * @return String
	 * @author zheng
	 */
	public static String subString(String str, int len) {
		if (str == null || ("").equals(str)) {
			return "";
		}
		byte[] strByte = null;
		try {
			strByte = str.getBytes("GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		int strLen = strByte.length;
		if (len >= strLen || len < 1) {
			return str;
		}
		int count = 0;
		for (int i = 0; i < len; i++) {
			int value = (int) strByte[i];
			if (value < 0) {
				count++;
			}
		}
		if (count % 2 != 0) {
			len = (len == 1) ? len + 1 : len - 1; 
		}
		
		return str.substring(0, len-1);
	}
}